using System;
using System.ComponentModel;
using System.Data;
using System.Security.Permissions;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;

namespace PS.WebParts.Rollup.FP
{
    class RollupPropertyDescriptor : PropertyDescriptor
    {
        private Type propertyType;
        private DataColumn column;

        public RollupPropertyDescriptor(DataColumn col, Type propType)
            : base(col.ColumnName, null)
        {
            this.propertyType = propType;
            this.column = col;
        }

        public override bool CanResetValue(object component)
        {
            return true;
        }

        public override Type ComponentType
        {
            get { return typeof(RollupViewResultItem); }
        }

        public override object GetValue(object component)
        {
            RollupViewResultItem resultItem = component as RollupViewResultItem;
            if (resultItem!=null)
            {
                object val = resultItem.ResultItem[column];
                if (val != null)
                {
                    if (column.ColumnName == "Modified")
                    {
                        DateTime dtVal;
                        DateTime.TryParse((string)val, out dtVal);
                        val = SPUtility.CreateISO8601DateTimeFromSystemDateTime(dtVal);
                    }
                }
                return   val;
            }
            else
                return null;
        }

        public override bool IsReadOnly
        {
            [SharePointPermission(SecurityAction.Demand, ObjectModel = true)]
            get { return true; }
        }

        public override Type PropertyType
        {
            get { return propertyType; }
        }

        public override void ResetValue(object component)
        {
        }

        public override void SetValue(object component, object value)
        {
        }

        public override bool ShouldSerializeValue(object component)
        {
            return true;
        }
    }
}
